import { baseApiUrl, path } from "../../utils/config";
import { newsInfo, comment, commentPost, newsLike } from '../../utils/api';
import Toast from '@vant/weapp/toast/toast';
const app = getApp();
Page({
  data: {
    baseImageUrl: baseApiUrl,
    user_id: app.globalData.user_id,
    id: "",

    title: "",
    created_at: "",
    content: "",
    comment: "",
    like_number: "",

    value: "",

    show: false,
    page: 1,
    last_page: 1,
    list: []
  },
  async onLoad(options) {
    let id = options.id;
    this.setData({ id });
    this.getDeta();
  },
  async getDeta() {
    let id = this.data.id;
    let { news } = await newsInfo({ id });
    let { title, created_at, content, comment, like_number } = news;
    // content = content?.replace(/\<img/gi, '<img style="width:100%;height:auto"');
    // content = content?.replace(/<video/gi, '<video style="width:100%"').replace(/<section/g, '<div').replace(/\/section>/g, '\div>');
    content = content?.replace(/\<img/gi, '<img style="width:100%;height:auto"')
      .replace(/<video/gi, '<video style="width:100%"')
      .replace(/<section/g, '<div')
      .replace(/\/section>/g, '\div>');
    this.setData({ title, created_at, content, comment, like_number });
  },
  async changeShow() {
    this.getList();
    this.setData({ show: true });
  },
  onClose() {
    let page = 1, list = [];
    this.setData({ show: false, page, list });
  },
  async getList() {
    let res = await comment({ data_id: this.data.id, page: this.data.page, limit: 10 });
    res = res.comment;
    let { data, last_page } = res;
    let list = this.data.page == 1 ? data : [...this.data.list, ...data];
    this.setData({ list, last_page });
  },
  loadmore() {
    let page = this.data.page;
    let last_page = this.data.last_page;
    if (page == last_page) return false;
    page += 1;
    this.setData({ page });
    this.getList();
  },
  async submit() {
    let id = this.data.id;
    let content = this.data.value;
    await commentPost({ id, content });
    Toast.success('提交成功');
  },
  async addLink(e) {
    let { type, id } = e.currentTarget.dataset;
    id = id ? id : this.data.id;
    await newsLike({ type, id });
    Toast.success('操作成功');
  },
  onShareAppMessage() {
    let poster = app.globalData.poster;
    return {
      path,
      imageUrl: poster
    }
  },
  onShareTimeline() { }
})